package com.dayaokeji.rhythmschoolstudent.client.common.questions_and_answers;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.utils.DateUtils;
import com.dayaokeji.rhythmschoolstudent.utils.FileUtil;
import com.dayaokeji.rhythmschoolstudent.utils.FilenameUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ImageUtil;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionGroup;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.ResourceApi;
import com.dayaokeji.server_api.domain.FileInfo;
import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import top.zibin.luban.Luban;

/**
 * 问答列表
 */
public class QuestionAndAnswersActivity extends BaseActivity {

    private static final int UPLOAD_ANSWER_IMG_REQUEST_CODE = 1001;

    public static final String EXTRA_REL_ID = "rel_id";
    public static final String EXTRA_REL_TYPE = "rel_type";
    public static final String EXTRA_FUNCTION = "function";
    private static final int FILE_STORE_PERMISSION_REQUEST_CODE = 10002;
    private static final int TAKE_PHOTO_PERMISSION_CODE = 10003;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    private static final ResourceApi resourceApi = ApiUtils.getApi(ResourceApi.class);
    private Call<ServerResponse<List<FileInfo>>> selectCall;

    private int relId;
    private int relType;
    private int function;
    private Call<ServerResponse<List<Integer>>> uploadCall;

    private final List<FileInfo> selfFiles = new ArrayList<>();
    private SelfAnswersFragment selfAnswersFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_and_answers);
        setSupportActionBar(toolbar);

        relId = getIntent().getIntExtra(EXTRA_REL_ID, -1);
        relType = getIntent().getIntExtra(EXTRA_REL_TYPE, -1);
        function = getIntent().getIntExtra(EXTRA_FUNCTION, -1);

        if (relId == -1 || relType == -1 || function == -1) {
            ToastUtils.warning(R.string.data_incorrect);
            return;
        }

        init();
    }

    private void init() {
        setupView();
        final UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo == null) {
            ToastUtils.info(R.string.data_incorrect);
            ActivityStackManager.finish();
            return;
        }
        setFragment();
        checkStorePermission();
        checkoutCameraPermission();
    }

    private void setupView() {
        if (!refreshLayout.isRefreshing()) {
            refreshLayout.autoRefresh();
        }

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                requestResourceList();
            }
        });
    }

    private void setFragment(){
        selfAnswersFragment = selfAnswersFragment == null ? SelfAnswersFragment.newInstance() : selfAnswersFragment;
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_content,selfAnswersFragment).commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.question_and_answers, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_upload_answer:
                if (AndPermission.hasPermissions(QuestionAndAnswersActivity.this, PermissionGroup.CAMERA_AND_STORE)) {
                    ImageUtil.captureImageByCamera(this, UPLOAD_ANSWER_IMG_REQUEST_CODE);
                } else {
                    checkoutCameraPermission();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void requestResourceList() {
        selectCall = resourceApi.select(relId, relType, function);
        selectCall.enqueue(new ServerCallback<List<FileInfo>>() {
            @Override
            public void onResponse(boolean success, ServerResponse<List<FileInfo>> response) {
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                }
                if (success) {
                    selfFiles.clear();
                    String userId = UserUtils.getUserInfo().getId();
                    for (FileInfo fileInfo : response.getBody()) {
                        if (fileInfo.getCreateUser().equals(userId)) {
                            selfFiles.add(fileInfo);
                        }
                    }
                    if (selfAnswersFragment != null) {
                        selfAnswersFragment.setData(selfFiles);
                    }
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<List<FileInfo>>> call, Throwable t) {
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                }
                super.onFailure(call, t);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (UPLOAD_ANSWER_IMG_REQUEST_CODE == requestCode) {
            if (resultCode != RESULT_CANCELED) {
                final File captureImageFile = ImageUtil.getCaptureImageFile();
                if (captureImageFile != null) {
                    compressionImageFile(captureImageFile.getAbsolutePath());
                }
            }
        }
    }

    /**
     * 上传文件
     *
     * @param filePath
     * @param file
     */
    private void uploadFileRequest(String filePath, File file, final ProgressDialog progressDialog) {
        String fileExtension = FilenameUtils.getExtension(filePath);
        final String fileName = UserUtils.getUserInfo().getName() + "-" + UserUtils.getUserInfo().getWorkNo() + "-" + DateUtils.format(System.currentTimeMillis(), DateUtils.FORMAT_DATE) + "." + fileExtension;
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("myfiles", fileName, requestBody);
        uploadCall = resourceApi.upload(filePart,
                RequestBody.create(MediaType.parse("text/plain"), String.valueOf(FileUtil.getFileType(fileExtension))),
                RequestBody.create(MediaType.parse("text/plain"), fileName),
                RequestBody.create(MediaType.parse("text/plain"), String.valueOf(function)),
                RequestBody.create(MediaType.parse("text/plain"), String.valueOf(relId)),
                RequestBody.create(MediaType.parse("text/plain"), String.valueOf(Boolean.FALSE)));
        uploadCall.enqueue(new ServerCallback<List<Integer>>() {
            @Override
            public void onResponse(boolean success, ServerResponse<List<Integer>> response) {
                if (success) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    ToastUtils.success("上传成功");
                    requestResourceList();
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<List<Integer>>> call, Throwable t) {
                super.onFailure(call, t);
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
            }
        });
    }

    /**
     * 压缩文件
     *
     * @param filePath
     */
    @SuppressLint("CheckResult")
    private void compressionImageFile(final String filePath) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在上传...");
        progressDialog.show();

        Flowable.just(filePath).observeOn(Schedulers.io()).map(new Function<String, File>() {
            @Override
            public File apply(String s) throws Exception {
                File file = Luban.with(QuestionAndAnswersActivity.this).load(s).get(s);
                if (file == null) {
                    file = new File(s);
                }
                return file;
            }
        }).subscribe(new Consumer<File>() {
            @Override
            public void accept(File file) throws Exception {
                if (file != null) {
                    final String fileName = UserUtils.getUserInfo().getName() + "-" + UserUtils.getUserInfo().getWorkNo() + "-" + DateUtils.format(System.currentTimeMillis(), DateUtils.FORMAT_DATE) + "." + FilenameUtils.getExtension(filePath);
                    File newFile = new File(file.getParent(), fileName);
                    boolean b = file.renameTo(newFile);
                    Logger.d("composer file rename = " + newFile.getAbsolutePath());
                    if (b) {
                        uploadFileRequest(filePath, newFile, progressDialog);
                    }
                }else{
                    ToastUtils.warning("压缩文件失败");
                }
            }
        });
    }

    /**
     * 检查存储权限
     */
    private void checkStorePermission() {
        addDisposable(PermissionUtil.checkStorePermission(QuestionAndAnswersActivity.this).subscribe(storeConsumer));
    }

    private Consumer storeConsumer = new Consumer<Boolean>() {
        @Override
        public void accept(Boolean aBoolean) throws Exception {
            if (!aBoolean) {
                checkStorePermission();
            }
        }
    };

    /**
     * 检查拍照权限
     */
    private void checkoutCameraPermission() {
        addDisposable(PermissionUtil.checkCameraPermission(QuestionAndAnswersActivity.this).subscribe(cameraConsumer));
    }

    private Consumer cameraConsumer = new Consumer<Boolean>() {
        @Override
        public void accept(Boolean aBoolean) throws Exception {
            checkoutCameraPermission();
        }
    };

    @Override
    protected void onDestroy() {
        if (selectCall != null) {
            selectCall.cancel();
        }
        if (uploadCall != null) {
            uploadCall.cancel();
        }
        super.onDestroy();
    }
}
